package com.runa.monitor.platinterface.backwork.impl;

import com.alibaba.fastjson.JSONObject;
import com.runa.monitor.comm.dto.newComm.AsynResult;
import com.runa.monitor.platinterface.backwork.function.TaskFunction;
import com.runa.monitor.platinterface.mqtt.MqttUtil;
import com.runa.monitor.platinterface.netservice.connect.commstatus.CommStatus;
import com.runa.rccprotocol.dto.param.ReadMeterPeriod;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class NetEquReadTaskFunction implements TaskFunction<Void, Object, Void> {

    private final String task;

    private final String holdInfo;

    private final String netEquId;

    private final int priority;

    public NetEquReadTaskFunction(String task, String holdInfo, String netEquId, int priority) {
        this.task = task;
        this.holdInfo = holdInfo;
        this.netEquId = netEquId;
        this.priority = priority;
    }

    @Override
    public void setStatus(Void s) {}

    @Override
    public void doApply(CommStatus status, Object object) {
        log.info("NetEquReadTaskFunction daApply {} {}", status, JSONObject.toJSONString(object));
        AsynResult asynResult = AsynResult.success();
        asynResult.setTask(task);
        asynResult.setHoldInfo(holdInfo);
        asynResult.setIdentity(netEquId);
        if (CommStatus.OK.equals(status)) {
            if (object instanceof List) {
                List list = (List) object;
                for (Object obj : list) {
                    if (obj instanceof ReadMeterPeriod) {
                        asynResult.setContent(((ReadMeterPeriod) obj).getPeriod());
                        MqttUtil.send("comm/net/period", asynResult);
                    }
                }
            }
        } else if (CommStatus.OffLine.equals(status)) {
            asynResult.offlineSetting();
        } else if (CommStatus.TimeOut.equals(status)) {
            asynResult.timeoutSetting();
        }
        MqttUtil.send(MqttUtil.topicOfNoneContent, asynResult);
    }

    @Override
    public Void waitResult() {
        return null;
    }

    @Override
    public String getSerial() {
        return null;
    }

    @Override
    public int getPriority() {
        return priority;
    }
}
